package sk.octopuss.archery.security;
import java.util.ArrayList;
import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import sk.octopuss.archery.domain.Role;

@Service("userAssembler")
public class UserAssembler {
	  @Transactional(readOnly = true)
	  User buildUserFromUserEntity(final sk.octopuss.archery.domain.User userEntity) {

	    final String username = userEntity.getUsername();
	    final String password = userEntity.getPassword();
	    final boolean enabled = userEntity.isActive();
	    final boolean accountNonExpired = userEntity.isActive();
	    final boolean credentialsNonExpired = userEntity.isActive();
	    final boolean accountNonLocked = userEntity.isActive();
	    

	    final Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
	    for (final Role role : userEntity.getRoles()) {
	      authorities.add(new GrantedAuthorityImpl(role.getName()));
	    }

	    final User user = new User(username, password, enabled,
	      accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
	    return user;
	  }
}
